﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using GameSchool.DAL;
using GameSchool.Models;
using GameSchool.Models.AccountModels;
using GameSchool.ViewModels.Course;

namespace GameSchool.Controllers
{
    [Authorize]
    public class CourseController : Controller
    {
        private ICourseRepository m_rep;

        public CourseController()
        {
            m_rep = new CourseRepository(new gsEntities());
        }

        public CourseController(ICourseRepository rep)
        {
            m_rep = rep;
        }

        [HttpPost]
        [Authorize(Roles = "Kennari")]
        public PartialViewResult AddStudent(int id, string studentFullname, bool isInstructor)
        {
            string userName = studentFullname.Split(new char[] { '(', ')' })[1];
            Guid userId = (Guid) Membership.GetUser(userName).ProviderUserKey;

            var added = m_rep.AddStudentToCourse(id, userId, isInstructor);
            m_rep.Save();

            return PartialView("AddStudentPartial", added);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Create()
        {
            var viewModel = new CreateViewModel();
            viewModel.course = new Course();
            viewModel.semesters = new SelectList(m_rep.GetSemesters(), "SemesterID", "SemesterName");
            viewModel.teachers = new SelectList(m_rep.GetTeachers(), "Key", "Value");

            return View(viewModel);
        }

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult Create(Course course)
        {
            if (ModelState.IsValid)
            {
                m_rep.InsertCourse(course);
                m_rep.Save();

                return RedirectToAction("List", new { courseCreated = course.Name });
            }
            else
            {
                ModelState.AddModelError("", "Það virðist eitthvað vera að innskráningunni. Vinsamlega farðu yfir innsláttinn og reyndu aftur.");
            }

            var viewModel = new CreateViewModel();
            viewModel.course = course;
            viewModel.semesters = new SelectList(m_rep.GetSemesters(), "SemesterID", "SemesterName");
            viewModel.teachers = new SelectList(m_rep.GetTeachers().OrderBy(i => i.Value), "Key", "Value");

            return View(viewModel);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Edit(int id)
        {
            var viewModel = new CreateViewModel();
            viewModel.course = m_rep.GetCourseById(id);
            viewModel.semesters = new SelectList(m_rep.GetSemesters(), "SemesterID", "SemesterName", viewModel.course.SemesterID);
            viewModel.teachers = new SelectList(m_rep.GetTeachers(), "Key", "Value", viewModel.course.TeacherUserID);

            return View(viewModel);
        }

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult Edit(Course course, int id)
        {
            if (ModelState.IsValid)
            {
                var courseToUpdate = m_rep.GetCourseById(id);
                courseToUpdate.Name = course.Name;
                courseToUpdate.Code = course.Code;
                courseToUpdate.Description = course.Description;
                courseToUpdate.SemesterID = course.SemesterID;
                courseToUpdate.TeacherUserID = course.TeacherUserID;
                courseToUpdate.Credits = course.Credits;
                courseToUpdate.IsActive = course.IsActive;

                m_rep.Save();

                return RedirectToAction("List", new { courseUpdated = course.Name });
            }
            else
            {
                ModelState.AddModelError("", "Það virðist eitthvað vera að innskráningunni. Vinsamlega farðu yfir innsláttinn og reyndu aftur.");
            }

            var viewModel = new CreateViewModel();
            viewModel.course = m_rep.GetCourseById(id);
            viewModel.semesters = new SelectList(m_rep.GetSemesters(), "SemesterID", "SemesterName", viewModel.course.SemesterID);
            viewModel.teachers = new SelectList(m_rep.GetTeachers(), "Key", "Value", viewModel.course.TeacherUserID);

            return View(viewModel);
        }

        [Authorize(Roles = "Kennari")]
        public ActionResult EditRules(int id)
        {
            var viewModel = new EditRulesViewModel();
            viewModel.courseRules = m_rep.GetCourseRules(id);

            return View(viewModel);
        }

        [Authorize]
        public ActionResult List()
        {
            var viewModel = new ListViewModel();
            var currentUser = Membership.GetUser();

            if (User.IsInRole("Admin"))
            {
                viewModel.coursesAdmin = m_rep.GetCoursesAdmin();
                return View("ListAdmin", viewModel);
            }
            else if (User.IsInRole("Kennari"))
            {
                viewModel.coursesTeacher = m_rep.GetCoursesTeacher((Guid)currentUser.ProviderUserKey);
                return View("ListTeacher", viewModel);
            }
            else if (User.IsInRole("Nemandi"))
            {
                viewModel.coursesStudent = m_rep.GetCoursesStudent((Guid)currentUser.ProviderUserKey);
                return View("ListStudent", viewModel);
            }

            throw new UnauthorizedAccessException("Þú virðist ekki vera í réttri notendagrúppu. Hafðu samband við kerfisstjóra.");
        }

        [Authorize(Roles = "Kennari")]
        public ActionResult EditStudents(int id)
        {
            var viewModel = new EditStudentsViewModel();
            viewModel.courseStudents = m_rep.GetCourseStudents(id);
            viewModel.currentCourse = m_rep.GetCourseById(id);

            return View(viewModel);
        }

        [Authorize]
        public ActionResult GetStudents()
        {
            return Json(m_rep.GetStudents(), "text/html", JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "Kennari")]
        public void RemoveStudent(int id, Guid studentUserId)
        {
            m_rep.RemoveStudentFromCourse(id, studentUserId);
            m_rep.Save();
        }
    }
}
